package com.zhiwang.planet.ui.my

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatRadioButton
import com.zhiwang.planet.R
import com.zhiwang.planet.di.component.DaggerUserComponent
import com.zhiwang.planet.di.module.AccountModule
import com.zhiwang.planet.di.module.AutoDisposeModule
import com.zhiwang.planet.mvp.p.UserPresenter
import com.zhiwang.planet.mvvm.viewmodel.ShareViewModel
import com.zhiwang.planet.mvvm.viewmodel.main.sharedViewModels
import com.zhiwang.planet.ui.BaseActivity
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.TokenManager
import com.zhiwang.planet.util.setGone
import kotlinx.android.synthetic.main.activity_change_imei.*
import kotlinx.android.synthetic.main.invite_dialog_layout.*
import javax.inject.Inject

class ChangeImeiActivity : BaseActivity() {

    private lateinit var deviceId: String
    val TAG = "ChangeImeiActivity"

//    @Inject
//    lateinit var restApi: RestApi

    @Inject
    lateinit var userPresenter: UserPresenter

    val shareViewModel by   sharedViewModels<ShareViewModel>()

    override fun initInjection() {
        super.initInjection()
        DaggerUserComponent.builder()
                .appComponent(getAppComponent())
                .autoDisposeModule(AutoDisposeModule(this))
                .accountModule(AccountModule(this))
                .build()
                .inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_change_imei)
        setSupportActionBar(toolbar)
        buttons = arrayListOf(radio_imei1, radio_imei2, radio_imei3)
        renderDeviceId()
        setUpListener()
    }

    private fun setUpListener() {

        imei_radio_group.setOnCheckedChangeListener { group, checkedId ->

            val chckedIndex = buttons.indexOfFirst { it.id == checkedId }
            deviceId = deviceIds[chckedIndex]
        }
    }



    fun confirmUpdate(view: View) {
        update(deviceId)
    }

    fun update(imei: String) {
        userPresenter.updateDeviceId(imei, {
            Toaster.message("切换成功")
            TokenManager.saveDevice(imei)
            Log.i(TAG, "update: $shareViewModel")
            shareViewModel.deviceIdChange.value = true
            renderDeviceId()
        }, ::onError)
    }


    var deviceIds = ArrayList<String>()
    var deviceIdDescription = ArrayList<String>()
    lateinit var buttons: List<AppCompatRadioButton>


    @SuppressLint("MissingPermission", "HardwareIds")
    fun renderDeviceId() {

        deviceIds.clear()
        deviceIdDescription.clear()
        val telecomManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager


        when {

            // imei
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> retrieveImeiExcludeMeid(telecomManager)


            //failing
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> retrieveMDeviceId(telecomManager)

            else -> retrieveLegacyDeviceId(telecomManager)
        }

        setDeviceIds()
    }


    private fun setDeviceIds() {

        deviceIds.forEachIndexed { index, id ->
            buttons[index].text = deviceIdDescription[index]
            if (isUsing(id).isNotEmpty()) buttons[index].isChecked = true
        }

        val indexOfFirst = buttons.indexOfFirst { it.id == imei_radio_group.checkedRadioButtonId }

        deviceId = deviceIds[
                indexOfFirst
        ]
    }

    @RequiresApi(Build.VERSION_CODES.M)
    @SuppressLint("MissingPermission")
    private fun retrieveMDeviceId(telecomManager: TelephonyManager) {

//        radio_imei2.setGone()
        radio_imei3.setGone()

        deviceIds.add(telecomManager.getDeviceId(0))
        deviceIds.add(telecomManager.getDeviceId(1))
        deviceIdDescription.add("${deviceIds[0]}")
        deviceIdDescription.add("${deviceIds[1]}")


    }

    @SuppressLint("MissingPermission")
    private fun retrieveLegacyDeviceId(telecomManager: TelephonyManager) {

        radio_imei2.setGone()
        radio_imei3.setGone()

        deviceIds.add(telecomManager.deviceId)

        deviceIdDescription.add("${deviceIds[0]}  (legacy)")
    }


    @SuppressLint("NewApi", "MissingPermission")
    private fun retrieveImeiExcludeMeid(telecomManager: TelephonyManager) {

        val defaultImei = telecomManager.imei

        val meid0 = telecomManager.getMeid(0) ?: ""
        val meid1 = telecomManager.getMeid(1) ?: ""

        val meid = if (TextUtils.isEmpty(meid0)) meid1 else meid0


        val imei0 = telecomManager.getImei(0)?:""
        val imei1 = telecomManager.getImei(1)?:""

        //exclude meid
        val imei = when {
            TextUtils.isEmpty(meid) -> imei0
            TextUtils.equals(meid, imei0) -> imei1
            else -> imei0
        }

        deviceIds.add(imei0)
        deviceIds.add(imei1)
        deviceIds.add(meid)

        deviceIdDescription.add("$imei0 ${if (imei0 == defaultImei) "  (default)" else ""} ${isUsing(imei0)}")
        deviceIdDescription.add("$imei1 ${if (imei1 == defaultImei) "  (default)" else ""} ${isUsing(imei1)}")
        deviceIdDescription.add("$meid  (meid) ${isUsing(meid)}")

    }

    private fun isUsing(imei0: String): String {
        return if (TokenManager.getDeviceId() == imei0) "使用中"
        else ""
    }


    override fun onNavigateUp(): Boolean {
        onBackPressed()
        return super.onNavigateUp()
    }


}
